package com.lishe.lishe.lishe.module.mall.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.lishe.lishe.R;
import com.lishe.base.common.base.BaseFragment;
import com.lishe.lishe.lishe.common.Globals;

/**
 * Created by shino on 2017/9/20.
 */

public class GoodsDetailFragmentWeb extends BaseFragment {

    private WebView myWebView = null;
    private boolean isRequesting = false;
    private ProgressBar progressBar;
    //    private String url = "http://api.lishe.cn/index.php/goods/details/itemId/";
    private String url = Globals.LISHE_URL + "goods/details/itemId/";
    public final static int FILECHOOSER_RESULTCODE = 1001;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 1002;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private String itemId;
    WebSettings webSettings;

    public static GoodsDetailFragmentWeb newInstance(String itemId) {
        GoodsDetailFragmentWeb fragment = new GoodsDetailFragmentWeb();
        Bundle bundle = new Bundle();
        bundle.putString("itemId", itemId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        itemId = getArguments().getString("itemId");
        url = url + itemId;
        Log.e("url", url);
//        url = LSWebHelper.BASE_URL +"Home/Giftrecord/index?token="+LSWebHelper.getInstance().getToken();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_webview, null);
        initView(view);
        view.setOnTouchListener(this);
        return view;
    }

    private void initView(View v) {
        progressBar = v.findViewById(R.id.progress);
        myWebView = v.findViewById(R.id.webView);
        webSettings = myWebView.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

//支持插件
//        webSettings.setPluginsEnabled(true);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(true); //隐藏原生的缩放控件

//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        myWebView.clearCache(true);
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.setWebChromeClient(new MyWebChromeClient());
        isRequesting = true;
        myWebView.loadUrl(url);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            progressBar.setVisibility(View.VISIBLE);
            Log.e("url", url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            myWebView.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
        }
    }

    boolean isOnPause = false;

    @Override
    public void onPause() {
        myWebView.onPause();
        super.onPause();

    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        myWebView.onResume();
        super.onResume();

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        myWebView.destroy();
        super.onDestroy();
    }

    private class MyWebChromeClient<FileChooserParams> extends WebChromeClient {

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android 3.0+ 文件选择
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.4 为了支持安卓5.0和6.0等高版本系统
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(filePathCallback);
            return true;
        }
    }

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"),
                FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadCallbackAboveL = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        startActivityForResult(chooserIntent,
                FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }


    @Override
    public void onBackPressed() {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri result = (data == null || resultCode != getActivity().RESULT_OK) ? null : data
                .getData();
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadCallbackAboveL)
                return;
            if (result != null) {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
            } else {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
            }
            mUploadCallbackAboveL = null;
            // onActivityResultAboveL(requestCode, resultCode, data);
        }
    }
}
